// StreamDriverTestOpenCloseApp.cpp : Defines the entry point for the application.
//

#include "stdafx.h"

int WINAPI WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPTSTR     lpCmdLine,
                     int       nCmdShow)
{

	BOOL success = true;

	BOOL usedCommandLine = true;

	wprintf(L"StreamDriverTest App.\r\n");

	LPCTSTR   wstream;
	wstream =(LPCTSTR) lpCmdLine;

	DWORD cmdlineLength = wcslen(wstream);
	WCHAR thisStream[] = _T("COM1:");

	//Default to this sstream
	if (cmdlineLength ==0)
	{
		wstream = thisStream;
		usedCommandLine=false;
	}
	//Check for index no.
	else if (cmdlineLength ==1)
	{
		BYTE index =  (BYTE) lpCmdLine[0] - (BYTE) '0';
		if (index <7) 
		{
			thisStream[3] = (WCHAR)lpCmdLine[0];
			wstream = (LPCTSTR) thisStream;
			usedCommandLine=true;
		}
		//Otherwise default to this stream with index 1
		else
		{
			wstream = thisStream;
			usedCommandLine=false;
		}
	}
	//Otherwise default to this stream with index 1
	else 
	{
		wstream = thisStream;
		usedCommandLine=false;
	}

	wprintf(L"StreamDriverTest Open\\Close App: This app. just checks for the presence of a stream named in commandline.\r\n");
	wprintf(L"It just attempts to open and close the stream.\r\n");
	wprintf(L"Attempting to open stream %s\r\n",wstream);

	if (!usedCommandLine) 
	{
		wprintf(L" Defaulted to stream index 1 ... ie COM1:\tCan enter other index 0 to 9 in commandline.\r\n");
	}

	HANDLE hStr =  CreateFile(wstream, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);

	if (hStr == (HANDLE)-1)
    {
		wprintf(L"StreamDriverTest Open\\Close App: Cannot open stream:  %s\r\n",wstream);
		success = false;
	}
	else 
	{
		wprintf(L"StreamDriverTest Open\\Close App:: Openned stream: %s\r\n",wstream);
	}

    // Disconnect from driver.
	if (success) {
		BOOL res = CloseHandle(hStr);
		if (!res)
		{
			wprintf(L"StreamDriverTest Open\\Close App: Couldn't close stream: %s\r\n",wstream);
			success = false;
		}
		else 
		{
			wprintf(L"StreamDriverTest Open\\Close App: Closed stream: %s\r\n",wstream);
		}
	}

	//Report result
	if (success) wprintf(L"StreamDriverTest Open\\Close App: %s tested OK.\r\n",wstream); 
	else wprintf(L"StreamDriverTest Open\\Close App: %s failed one or more tests.\r\n",wstream);

	return 0;
}

